<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-09-02 15:56:28
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-09-22 14:41:33
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\SecurCheck\LedgerMessage\UserLedger\components\UserLedger.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, ref, unref, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { EmergencyEventType } from '@/api/Emergency/type'
import SecurCheckLedgerApi from '@/api/securcheck/LedgerMessage'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useDictStore } from '@/store/modules/dictData'
import { Dialog } from '@/components/Dialog'
import UserGasdev from './UserGasdev.vue'
import { BaseButton } from '@/components/Button'
import UserGasdevDetailVue from './UserGasdevDetail.vue'
const { required } = useValidator()
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<EmergencyEventType>>,
    default: () => null
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  },
  FormDisabled: {
    type: Boolean as PropType<boolean>,
    default: () => null
  }
})
const ids = ref()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const i = await SecurCheckLedgerApi.GetUserGasdev({
      userLedgerUuid: props?.currentRow?.uuid
    })
    return {
      list: i.rows
    }
  },
  fetchDelApi: async () => {
    const res = await SecurCheckLedgerApi.DeletUserGasdev(unref(ids)[0])
    return !!res
  },
  immediate: false
})
const DictStore = useDictStore()
//获取字典
DictStore.setDict('secur_mount_pos') //安装位置
const { loading, dataList } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const delLoading = ref(false)
//表格删除操作
const delData = async (row: any | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.uuid] : elTableExpose?.getSelectionRows().map((v: any) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const UserGasdevRef = ref()
const rules = reactive({
  userState: [required()],
  userNumebr: [required()],
  userName: [required()],
  gogasAddre: [required()],
  community: [required()],
  floorNo: [required()],
  unitNo: [required()],
  roomNo: [required()]
})
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    console.log(formData)
    return formData
  }
}
watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
    if (Object.keys(currentRow).length !== 0) {
      getList()
    }
  },
  {
    deep: true,
    immediate: true
  }
)
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: '序号',
    fixed: 'left',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'gasdevType',
    label: '名称',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'brand',
    label: '品牌',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'mountPos',
    label: '位置',
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.secur_mount_pos?.map((item) => {
        if (item.dictValue == cellValue) {
          return item.dictLabel
        }
      })
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'installDate',
    label: '安装时间',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: '操作',
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'detail')}>
                查看
              </span>

              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                删除
              </span>
            </>
          )
        }
      }
    }
  }
])
const dialogVisible = ref(false)
const saveLoading = ref(false)
const IsDetail = ref(false)
const { allSchemas } = useCrudSchemas(crudSchemas)
const Gasdev = ref()

const action = (row: any, type: string) => {
  dialogVisible.value = true
  Gasdev.value = row
  if (type == 'detail') {
    IsDetail.value = true
  } else {
    IsDetail.value = false
  }
}
const save = async () => {
  const write = unref(UserGasdevRef)
  const formData = await write?.submit()
  const res = await SecurCheckLedgerApi.AddUserGasdev({
    userLedgerUuid: props?.currentRow?.uuid,
    tbUserGasdevs: [formData]
  })
  console.log(res)
  if (res) {
    dialogVisible.value = false
    getList()
  }
}
defineExpose({
  submit
})
</script>

<template>
  <Form
    :disabled="props.FormDisabled"
    :rules="rules"
    @register="formRegister"
    :schema="formSchema"
  />
  <BaseButton
    type="primary"
    size="small"
    @click="action({}, 'add')"
    style="float: right; margin: 0 30px 10px 0px"
    ><Icon icon="ep:plus" :size="13" />新增</BaseButton
  >
  <Table
    :columns="allSchemas.tableColumns"
    :data="dataList"
    :loading="loading"
    @register="tableRegister"
  />
  <Dialog v-model="dialogVisible" title="关联设备" maxHeight="400px">
    <UserGasdevDetailVue v-if="IsDetail" :current-row="Gasdev" />
    <UserGasdev ref="UserGasdevRef" v-else :current-row="Gasdev" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save"> 提交 </BaseButton>
      <BaseButton @click="dialogVisible = false">关闭</BaseButton>
    </template>
  </Dialog>
</template>
<style scoped>
/* :deep(.el-col) {
  padding: 10px 15px 5px 0px !important;
}
#4099f5 */
:deep(.el-divider--horizontal) {
  border-top: 1px #4099f5 solid !important;
}
:deep(.el-divider__text) {
  color: #4099f5;
}
</style>
